#define _CRT_SECURE_NO_WARNINGS 1
#include<stdio.h>
//#include<stdlib.h>
#include<string.h>
void bubble_sort(void* base, int sz, int width, int (*cmp)(const void* e1, const void* e2));

int cmp_int(const void* e1, const void* e2)
{
	return *(int*)e1 - *(int*)e2;
}

void test1()
{
	int arr[10] = { 1,2,3,4,5,6,7,8,9,0 };
	int i;
	int sz = sizeof(arr) / sizeof(arr[0]);
	//qsort(arr, sz, sizeof(arr[0]), cmp_int);
	bubble_sort(arr, sz, sizeof(arr[0]), cmp_int);
	for (i = 0; i < sz; i++)
	{
		printf("%d", arr[i]);
	}

}

int cmp_float(const void* e1, const void* e2)
{
	/*return ((int)(*(float*)e1 - *(float*)e2));*/
	if (*(float*)e1 == *(float*)e2)
		return 0;
	else if (*(float*)e1 - *(float*)e2 > 0)
		return 1;
	else
		return -1;
}

void test2()
{
	float f[10] = { 1.1,2.2,3.4,5.4,4.2,5.8,8.2,8.3,9.1,10.2 };
	int i = 0;
	int sz = sizeof(f) / sizeof(f[0]);
	//qsort(f, sz, sizeof(f[0]), cmp_float);
	bubble_sort(f, sz, sizeof(f[0]), cmp_float);
	for (i = 0; i < sz; i++)
	{
		printf("%f\n", f[i]);
	}
}

struct Stu {
	char name[20];
	int age;
};

int cmp_Stu_by_name(const void* e1, const void* e2)
{
	return (strcmp(((struct Stu*)e1)->name, ((struct Stu*)e2)->name));
}

int cmp_Stu_by_age(const void* e1, const void* e2)
{
	return ((struct Stu*)e2)->age - ((struct Stu*)e1)->age;
}

void test3()
{
	struct Stu s[3] = { {"zhangsan",18},{"lisi",23},{"wangwu",20} };
	int i;
	int sz = sizeof(s) / sizeof(s[0]);
	//qsort(s, sz, sizeof(s[0]), cmp_Stu_by_name);
	//qsort(s, sz, sizeof(s[0]), cmp_Stu_by_age);
	bubble_sort(s, sz, sizeof(s[0]), cmp_Stu_by_age);
	bubble_sort(s, sz, sizeof(s[0]), cmp_Stu_by_name);
	for (i = 0; i < sz; i++)
	{
		printf("%d", s[i].age);
		//printf("\n");
		//printf("%s", s[i].name);
	}

}

void swap(char* buf1,char* buf2, int width)
{
	int i = 0;
	for (i = 0; i < width; i++)
	{
		char tmp = *buf1;
		*buf1 = *buf2;
		*buf2 = tmp;
		buf1++;
		buf2++;
	}
}

void bubble_sort(void* base, int sz, int width, int (*cmp)(const void* e1, const void* e2))
{
	int i = 0;
	for (i = 0; i < sz - 1; i++)
	{
		int j = 0;
		for (j = 0; j < sz - 1 - i; j++)
		{
			if (cmp((char*)base + j * width, (char*)base + (j + 1) * width) > 0)
			{
				swap((char*)base + j * width, (char*)base + (j + 1) * width, width);
			}
		}
	}
}


int main()
{
	/*int arr[10] = { 1,2,3,4,5,6,7,8,9,0 };
	int i;
	int sz = sizeof(arr) / sizeof(arr[0]);
	bubble_sort(arr, sz);
	for (i = 0; i < sz; i++)
	{
		printf("%d", arr[i]);
	}*/
	//test1();
	//test2();
	test3();
}



